package http

import (
	"furniture-server-gin/api/pkg/infrastructure/config"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// JWTAuthMiddleware JWT认证中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		authHeader := ctx.GetHeader("Authorization")
		if authHeader == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
			ctx.Abort()
			return
		}

		// 检查Bearer前缀
		tokenString := ""
		if strings.HasPrefix(authHeader, "Bearer ") {
			tokenString = authHeader[7:]
		} else {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
			ctx.Abort()
			return
		}

		// 解析和验证令牌
		claims, err := config.ParseToken(tokenString)
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			ctx.Abort()
			return
		}

		// 将用户信息存储在上下文中
		ctx.Set("user_id", claims.UserID)
		ctx.Set("username", claims.Username)
		ctx.Next()
	}
}

// CasbinMiddleware Casbin权限中间件
func CasbinMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 获取用户信息
		userID, exists := ctx.Get("user_id")
		if !exists {
			ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
			ctx.Abort()
			return
		}

		// 获取请求路径和方法
		obj := ctx.Request.URL.Path
		act := ctx.Request.Method

		// 检查权限
		enforcer := config.GetCasbinEnforcer()
		if enforcer == nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Casbin not initialized"})
			ctx.Abort()
			return
		}

		// 检查权限
		ok, err := enforcer.Enforce(userID, obj, act)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to enforce policy"})
			ctx.Abort()
			return
		}

		if !ok {
			ctx.JSON(http.StatusForbidden, gin.H{"error": "Insufficient permissions"})
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}
